import axios from 'axios'
import env from '../../build/env'
import iView from 'iview'
import Cookies from 'js-cookie';

let util = {};
util.title = function (title) {
    title = title ? title + ' - Home' : 'iView project';
    window.document.title = title;
};


const ajaxUrl = env === 'development'
    ? 'http://127.0.0.1:8089'
    : env === 'production'
        ? 'https://www.url.com'
        : 'https://debug.url.com';

//携带cookie信息
axios.defaults.withCredentials = true;

util.axios = axios.create({
    baseURL: ajaxUrl,
    timeout: 30000,
    // headers: {'Content-Type': 'application/json;charset=utf-8'}
});
// 拦截响应response，并做一些错误处理
util.axios.interceptors.response.use((response) => {
    const data = response.data
    if(data.code && data.code == 1000)
    {
        Cookies.remove('user');
    }
    return response;
}, function (error) {
    // Do something with response error
    if(error.response)
    {
        let status = error.response.status;
        switch (status)
        {
            case 404:
                iView.Notice.error({
                    title: '提示',
                    desc: '请求地址不存在'
                });
                break;
            default:

                break;
        }
        return Promise.reject(error);
    }

    let msg = error.message;
    if(msg = "Network Error")
    {
        iView.Notice.error({
            title: '提示',
            desc: 'Network Error'
        });
    }
});


util.session = function (key, value) {
    if (value === void(0)) {
        var lsVal = sessionStorage.getItem(key);
        if (lsVal && lsVal.indexOf('autostringify-') === 0) {
            return JSON.parse(lsVal.split('autostringify-')[1]);
        } else {
            return lsVal;
        }
    } else {
        if (typeof(value) === "object" || Array.isArray(value)) {
            value = 'autostringify-' + JSON.stringify(value);
        }
        return sessionStorage.setItem(key, value);
    }
}


//深拷贝
export const deepcopy = function (source) {
    if (!source) {
        return source;
    }
    let sourceCopy = source instanceof Array ? [] : {};
    for (let item in source) {
        sourceCopy[item] = typeof source[item] === 'object' ? deepcopy(source[item]) : source[item];
    }
    return sourceCopy;
};

util.deepcopy = deepcopy;


util.inOf = function (arr, targetArr) {
    let res = true;
    arr.map(item => {
        if (targetArr.indexOf(item) < 0) {
            res = false;
        }
    });
    return res;
};

util.oneOf = function (ele, targetArr) {
    if (targetArr.indexOf(ele) >= 0) {
        return true;
    } else {
        return false;
    }
};

util.getRouterObjByName = function (routers, name) {
    if (!name || !routers || !routers.length) {
        return null;
    }
    let routerObj = null;
    for (let item of routers) {
        if (item.name === name) {
            return item;
        }
        routerObj = util.getRouterObjByName(item.children, name);
        if (routerObj) {
            return routerObj;
        }
    }
    return null;
};

//面包屑
util.setCurrentPath = function (vm, name) {
    let currentPathArr = [
        {
            title: '首页',
            path: '/home',
            name: 'home_index'
        }
    ];

    if (name.name === 'home_index') {
        currentPathArr = [
            {
                title: '首页',
                path: '',
                name: 'home_index'
            }
        ];
    }
    else {
        let Arr = name.matched;
        Arr.forEach(item => {
            let router = util.getRouterObjByName(vm.$store.state.app.routers, item.name);
            if(router.title)
            {
                let currentPath = {
                    title: router.title,
                    path: name.name == item.name ? item.path : '',
                    name: item.name
                };
                currentPathArr.push(currentPath);
            }
        });
    }
    // 修改面包屑
    vm.$store.commit('setCurrentPath', currentPathArr);
    return currentPathArr;
}

/**
 * 打开tab
 * @param vm
 * @param name
 * @param argu
 * @param query
 */
util.openNewPage = function (vm, name, argu, query) {
    let pageOpenedList = vm.$store.state.app.pageOpenedList;
    let openedPageLen = pageOpenedList.length;
    let i = 0;
    let tagHasOpened = false;
    while (i < openedPageLen) {
        if (name === pageOpenedList[i].name) { // 页面已经打开
            vm.$store.commit('pageOpenedList', {
                index: i,
                argu: argu,
                query: query
            });
            tagHasOpened = true;
            break;
        }
        i++;
    }

    if (!tagHasOpened) {
        let tag = util.getRouterObjByName(vm.$store.state.app.tagsList, name);
        if (tag) {
            tag = tag.children ? tag.children[0] : tag;
            if (argu) {
                tag.argu = argu;
            }
            if (query) {
                tag.query = query;
            }
            vm.$store.commit('increateTag', tag);
        }
    }
    vm.$store.commit('setCurrentPageName', name);
};

export default util;